/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.netbeans.modules.php.analysis.ui.options;

import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentListener;
import org.netbeans.modules.php.analysis.commands.Psalm;
import org.netbeans.modules.php.analysis.options.AnalysisOptions;
import org.netbeans.modules.php.analysis.options.AnalysisOptionsValidator;
import org.netbeans.modules.php.analysis.ui.AnalysisDefaultDocumentListener;
import org.netbeans.modules.php.analysis.options.ValidatorPsalmParameter;
import org.netbeans.modules.php.analysis.util.AnalysisUiUtils;
import org.netbeans.modules.php.api.validation.ValidationResult;
import org.openide.awt.HtmlBrowser;
import org.openide.awt.Mnemonics;
import org.openide.util.ChangeSupport;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;

public class PsalmOptionsPanel extends AnalysisCategoryPanel {

    private static final long serialVersionUID = 1199550925948622972L;

    private final ChangeSupport changeSupport = new ChangeSupport(this);

    /**
     * Creates new form PsalmOptionsPanel
     */
    public PsalmOptionsPanel() {
        super();
        initComponents();
        init();
    }

    @NbBundle.Messages({
        "# {0} - short script name",
        "# {1} - long script name",
        "PsalmOptionsPanel.hint=Full path of Psalm script (typically {0} or {1}).",})
    private void init() {
        psalmHintLabel.setText(Bundle.PsalmOptionsPanel_hint(Psalm.NAME, Psalm.LONG_NAME));
        psalmLevelComboBox.removeAllItems();
        // NETBEANS-2974
        // allow empty level option to use a level of a configuration file
        psalmLevelComboBox.addItem(""); // NOI18N
        for (int i = AnalysisOptions.PSALM_MIN_LEVEL; i <= AnalysisOptions.PSALM_MAX_LEVEL; i++) {
            psalmLevelComboBox.addItem(String.valueOf(i));
        }
        // add listener
        DocumentListener defaultDocumentListener = new AnalysisDefaultDocumentListener(() -> fireChange());
        psalmTextField.getDocument().addDocumentListener(defaultDocumentListener);
        psalmConfigurationTextField.getDocument().addDocumentListener(defaultDocumentListener);
        psalmMemoryLimitTextField.getDocument().addDocumentListener(defaultDocumentListener);
        psalmLevelComboBox.addActionListener(e -> fireChange());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        psalmLabel = new JLabel();
        psalmTextField = new JTextField();
        psalmBrowseButton = new JButton();
        psalmSearchButton = new JButton();
        psalmHintLabel = new JLabel();
        psalmLevelLabel = new JLabel();
        psalmLevelComboBox = new JComboBox<>();
        psalmMemoryLimitLabel = new JLabel();
        psalmMemoryLimitTextField = new JTextField();
        psalmConfigurationLabel = new JLabel();
        psalmConfigurationTextField = new JTextField();
        psalmConfigurationInfoLabel = new JLabel();
        psalmConfiturationBrowseButton = new JButton();
        psalmNoteLabel = new JLabel();
        psalmMinVersionInfoLabel = new JLabel();
        psalmLearnMoreLabel = new JLabel();

        psalmLabel.setLabelFor(psalmTextField);
        Mnemonics.setLocalizedText(psalmLabel, NbBundle.getMessage(PsalmOptionsPanel.class, "PsalmOptionsPanel.psalmLabel.text")); // NOI18N

        Mnemonics.setLocalizedText(psalmBrowseButton, NbBundle.getMessage(PsalmOptionsPanel.class, "PsalmOptionsPanel.psalmBrowseButton.text")); // NOI18N
        psalmBrowseButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                psalmBrowseButtonActionPerformed(evt);
            }
        });

        Mnemonics.setLocalizedText(psalmSearchButton, NbBundle.getMessage(PsalmOptionsPanel.class, "PsalmOptionsPanel.psalmSearchButton.text")); // NOI18N
        psalmSearchButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                psalmSearchButtonActionPerformed(evt);
            }
        });

        Mnemonics.setLocalizedText(psalmHintLabel, "HINT"); // NOI18N

        psalmLevelLabel.setLabelFor(psalmLevelComboBox);
        Mnemonics.setLocalizedText(psalmLevelLabel, NbBundle.getMessage(PsalmOptionsPanel.class, "PsalmOptionsPanel.psalmLevelLabel.text")); // NOI18N

        psalmLevelComboBox.setModel(new DefaultComboBoxModel<>(new String[] { "0", "1", "2", "3", "4", "5", "6", "7" }));

        psalmMemoryLimitLabel.setLabelFor(psalmMemoryLimitTextField);
        Mnemonics.setLocalizedText(psalmMemoryLimitLabel, NbBundle.getMessage(PsalmOptionsPanel.class, "PsalmOptionsPanel.psalmMemoryLimitLabel.text")); // NOI18N

        psalmConfigurationLabel.setLabelFor(psalmConfigurationTextField);
        Mnemonics.setLocalizedText(psalmConfigurationLabel, NbBundle.getMessage(PsalmOptionsPanel.class, "PsalmOptionsPanel.psalmConfigurationLabel.text")); // NOI18N

        Mnemonics.setLocalizedText(psalmConfigurationInfoLabel, NbBundle.getMessage(PsalmOptionsPanel.class, "PsalmOptionsPanel.psalmConfigurationInfoLabel.text")); // NOI18N

        Mnemonics.setLocalizedText(psalmConfiturationBrowseButton, NbBundle.getMessage(PsalmOptionsPanel.class, "PsalmOptionsPanel.psalmConfiturationBrowseButton.text")); // NOI18N
        psalmConfiturationBrowseButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                psalmConfiturationBrowseButtonActionPerformed(evt);
            }
        });

        Mnemonics.setLocalizedText(psalmNoteLabel, NbBundle.getMessage(PsalmOptionsPanel.class, "PsalmOptionsPanel.psalmNoteLabel.text")); // NOI18N

        Mnemonics.setLocalizedText(psalmMinVersionInfoLabel, NbBundle.getMessage(PsalmOptionsPanel.class, "PsalmOptionsPanel.psalmMinVersionInfoLabel.text")); // NOI18N

        Mnemonics.setLocalizedText(psalmLearnMoreLabel, NbBundle.getMessage(PsalmOptionsPanel.class, "PsalmOptionsPanel.psalmLearnMoreLabel.text")); // NOI18N
        psalmLearnMoreLabel.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent evt) {
                psalmLearnMoreLabelMousePressed(evt);
            }
            public void mouseEntered(MouseEvent evt) {
                psalmLearnMoreLabelMouseEntered(evt);
            }
        });

        GroupLayout layout = new GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(psalmMinVersionInfoLabel)
                    .addComponent(psalmLearnMoreLabel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(psalmConfigurationLabel)
                    .addComponent(psalmLabel)
                    .addComponent(psalmLevelLabel)
                    .addComponent(psalmNoteLabel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(psalmMemoryLimitLabel))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addComponent(psalmConfigurationInfoLabel)
                            .addComponent(psalmLevelComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                            .addComponent(psalmMemoryLimitTextField, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 62, Short.MAX_VALUE))
                    .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                            .addComponent(psalmConfigurationTextField)
                            .addComponent(psalmTextField, GroupLayout.Alignment.LEADING)
                            .addGroup(GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(psalmHintLabel)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(psalmBrowseButton)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(psalmSearchButton))
                            .addComponent(psalmConfiturationBrowseButton)))))
        );
        layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(psalmLabel)
                    .addComponent(psalmTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(psalmBrowseButton)
                    .addComponent(psalmSearchButton))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(psalmHintLabel)
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(psalmConfigurationLabel)
                    .addComponent(psalmConfigurationTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(psalmConfiturationBrowseButton))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(psalmConfigurationInfoLabel)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(psalmLevelLabel)
                    .addComponent(psalmLevelComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(psalmMemoryLimitLabel)
                    .addComponent(psalmMemoryLimitTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(psalmNoteLabel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(psalmMinVersionInfoLabel)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(psalmLearnMoreLabel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        );

        psalmLabel.getAccessibleContext().setAccessibleName(NbBundle.getMessage(PsalmOptionsPanel.class, "PsalmOptionsPanel.psalmLabel.AccessibleContext.accessibleName")); // NOI18N
    }// </editor-fold>//GEN-END:initComponents

    private void psalmBrowseButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_psalmBrowseButtonActionPerformed
        File file = AnalysisUiUtils.browsePsalm();
        if (file != null) {
            psalmTextField.setText(file.getAbsolutePath());
        }
    }//GEN-LAST:event_psalmBrowseButtonActionPerformed

    private void psalmSearchButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_psalmSearchButtonActionPerformed
        String psalm = AnalysisUiUtils.searchPsalm();
        if (psalm != null) {
            psalmTextField.setText(psalm);
        }
    }//GEN-LAST:event_psalmSearchButtonActionPerformed

    private void psalmLearnMoreLabelMouseEntered(MouseEvent evt) {//GEN-FIRST:event_psalmLearnMoreLabelMouseEntered
        evt.getComponent().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    }//GEN-LAST:event_psalmLearnMoreLabelMouseEntered

    private void psalmLearnMoreLabelMousePressed(MouseEvent evt) {//GEN-FIRST:event_psalmLearnMoreLabelMousePressed
        try {
            URL url = new URL("https://github.com/vimeo/psalm"); // NOI18N
            HtmlBrowser.URLDisplayer.getDefault().showURL(url);
        } catch (MalformedURLException ex) {
            Exceptions.printStackTrace(ex);
        }
    }//GEN-LAST:event_psalmLearnMoreLabelMousePressed

    private void psalmConfiturationBrowseButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_psalmConfiturationBrowseButtonActionPerformed
        File file = AnalysisUiUtils.browsePsalmConfiguration();
        if (file != null) {
            psalmConfigurationTextField.setText(file.getAbsolutePath());
        }
    }//GEN-LAST:event_psalmConfiturationBrowseButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private JButton psalmBrowseButton;
    private JLabel psalmConfigurationInfoLabel;
    private JLabel psalmConfigurationLabel;
    private JTextField psalmConfigurationTextField;
    private JButton psalmConfiturationBrowseButton;
    private JLabel psalmHintLabel;
    private JLabel psalmLabel;
    private JLabel psalmLearnMoreLabel;
    private JComboBox<String> psalmLevelComboBox;
    private JLabel psalmLevelLabel;
    private JLabel psalmMemoryLimitLabel;
    private JTextField psalmMemoryLimitTextField;
    private JLabel psalmMinVersionInfoLabel;
    private JLabel psalmNoteLabel;
    private JButton psalmSearchButton;
    private JTextField psalmTextField;
    // End of variables declaration//GEN-END:variables

    @NbBundle.Messages("PsalmOptionsPanel.category.name=Psalm")
    @Override
    public String getCategoryName() {
        return Bundle.PsalmOptionsPanel_category_name();
    }

    @Override
    public void addChangeListener(ChangeListener listener) {
        changeSupport.addChangeListener(listener);
    }

    @Override
    public void removeChangeListener(ChangeListener listener) {
        changeSupport.removeChangeListener(listener);
    }

    @Override
    public void update() {
        AnalysisOptions options = AnalysisOptions.getInstance();
        setPsalmPath(options.getPsalmPath());
        setPsalmConfigurationPath(options.getPsalmConfigurationPath());
        setPsalmLevel(options.getPsalmLevel());
        setPsalmMemoryLimit(options.getPsalmMemoryLimit());
    }

    @Override
    public void applyChanges() {
        AnalysisOptions options = AnalysisOptions.getInstance();
        options.setPsalmPath(getPsalmPath());
        options.setPsalmConfigurationPath(getPsalmConfigurationPath());
        options.setPsalmLevel(getPsalmLevel());
        options.setPsalmMemoryLimit(getPsalmMemoryLimit());
    }

    @Override
    public boolean isChanged() {
        String saved = AnalysisOptions.getInstance().getPsalmPath();
        String current = getPsalmPath();
        if (saved == null ? !current.isEmpty() : !saved.equals(current)) {
            return true;
        }
        saved = AnalysisOptions.getInstance().getPsalmConfigurationPath();
        current = getPsalmConfigurationPath();
        if (saved == null ? !current.isEmpty() : !saved.equals(current)) {
            return true;
        }
        String savedString = AnalysisOptions.getInstance().getPsalmLevel();
        String currentString = getPsalmLevel();
        return !savedString.equals(currentString);
    }

    @Override
    public ValidationResult getValidationResult() {
        return new AnalysisOptionsValidator()
                .validatePsalm(ValidatorPsalmParameter.create(this))
                .getResult();
    }

    void fireChange() {
        changeSupport.fireChange();
    }

    public String getPsalmPath() {
        return psalmTextField.getText().trim();
    }

    private void setPsalmPath(String path) {
        psalmTextField.setText(path);
    }

    public String getPsalmConfigurationPath() {
        return psalmConfigurationTextField.getText().trim();
    }

    private void setPsalmConfigurationPath(String path) {
        psalmConfigurationTextField.setText(path);
    }

    public String getPsalmLevel() {
        return (String) psalmLevelComboBox.getSelectedItem();
    }

    private void setPsalmLevel(String level) {
        psalmLevelComboBox.setSelectedItem(level);
    }

    public String getPsalmMemoryLimit() {
        return psalmMemoryLimitTextField.getText().trim();
    }

    private void setPsalmMemoryLimit(String memoryLimit) {
        psalmMemoryLimitTextField.setText(memoryLimit);
    }
}
